package com.data;

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.util.Log;

import com.bean.ScoreBean;
import com.constant.Constant;
import com.net.ClientError;
import com.net.ClientException;
import com.net.RequestParameter;
/**
 * 成绩查询接口，
 * 请求参数⑤个：
 * <url> :登陆时获取
 * 
 * 按学期查询时四个post参数如下:
 * <__VIEWSTATE> :由成绩查询状态接口返回
 * <ddlXN> ： 查询时间
 * <ddlXQ> ： 学期
 * <Button1> ：按学习查询
 * 
 * 按学年查询时,post参数为三个:
 * <ddlXQ参数为null
 * 
 * <name></name> 姓名
 * @author mjh
 *
 */
public final class ScoreQueryData extends BaseData
{

	private final static String TAG = "score_query_data";
	
	private ArrayList<ScoreBean> mScoreList;
	
	@Override
	public void startParse(RequestParameter parameter) throws Exception
	{
		Log.i(TAG, "开始获取成绩查询数据");
		
		String url = parameter.getValue("url");
		parameter.remove("url");
		String name = parameter.getValue("name");
		parameter.remove("name");
		
		String param = encodeParameters(parameter);
		
		// 移除post请求时的第一个数据&符号
		param = param.replaceFirst("&", "");
		//param = param.replaceAll(name, URLEncoder.encode(name, "utf-8"));
		
		String stream = openConnection(url, param, name);
		if ( param == null )
			return;
		
		readStream(stream);
		
	} // startParse
	
	private String openConnection(final String urls, final String postData, final String name) throws Exception
	{
		URL url = new URL(urls.replaceAll(name, URLEncoder.encode(name, "utf-8")));
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setDoOutput(true);
		connection.setRequestMethod("POST");
		connection.setRequestProperty("Accept", "text/html, application/xhtml+xml, */*");
		connection.setRequestProperty("Referer", urls.replaceAll(name, URLEncoder.encode(name, "utf-8")));
		connection.setRequestProperty("Host", "jwc.xhu.edu.cn");
		connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		connection.setUseCaches(false);
		connection.setConnectTimeout(Constant.SET_CONNECTION_TIMEOUT);
		connection.setReadTimeout(Constant.SET_READ_TIMEOUT);
		// 设置不自动重定向，用户用户Location
		connection.setInstanceFollowRedirects(false);
		
		OutputStream out = connection.getOutputStream();
		out.write(postData.getBytes());
		out.close();
		connection.connect();
		if(connection.getResponseCode() != 200)
		{
			Log.i(TAG, "连接失败,失败原因:" + connection.getResponseCode());
			throw new ClientException( connection.getResponseCode() + "", ClientError.ERROR_CONNECTION);
			
		}
		
		return getWebSource(connection.getInputStream(), "gb2312");
		
	} // openConnection
	
	
	/**
	 * 数据格式如下:
	 * <table class="datelist" cellspacing="0" cellpadding="3" border="0" id="Datagrid1" width="100%"> 
	 <tbody>
	  <tr class="datelisthead"> 
	   <td>学年</td>
	   <td>学期</td>
	   <td>课程代码</td>
	   <td>课程名称</td>
	   <td>课程性质</td>
	   <td>学分</td>
	   <td>绩点</td>
	   <td>成绩</td>
	   <td>重修成绩</td>
	   <td>课程开课学院</td> 
	  </tr>
	  <tr> 
	   <td>2011-2012</td>
	   <td>1</td>
	   <td>8400171</td>
	   <td>Windows应用程序设计</td>
	   <td>专业选修</td>
	   <td>3.0</td>
	   <td>1.8</td>
	   <td>68</td>
	   <td>&nbsp;</td>
	   <td>数学与计算机学院</td> 
	  </tr>
	 </tbody>
	</table>
	
	<table class="datelist">..</table>
	<table class="datelist">..</table>
	<table class="datelist">..</table>
	<table class="datelist" cellspacing="0" cellpadding="3" border="0" id="Datagrid3" width="100%"> 
	 <tbody>
	  <tr class="datelisthead"> 
	   <td>课程代码</td>
	   <td>课程名称</td>
	   <td>学分</td>
	   <td>课程性质</td>
	   <td>最高成绩值</td>
	   <td>课程归属</td> 
	  </tr>
	  <tr class="alt"> 
	   <td>5100090</td>
	   <td>大学日语(1)</td>
	   <td>4.0</td>
	   <td>公共必修</td>
	   <td>55</td>
	   <td>&nbsp;</td> 
	  </tr> 
	 </tbody>
	</table>
	 * @param stream
	 */
	private void readStream(final String stream) throws Exception
	{
		Log.i(TAG, "开始解析返回成绩html数据");
		
		Document document = Jsoup.parse(stream);
		Elements tables = document.getElementsByClass("datelist");
//		System.out.println(tables.html().toString());
		// 查询大小为4,当前查询的返回数据在第0个位置,未通过的在第4个位置
		if(tables == null)
		{
			Log.i(TAG, "成绩查询失败");
			throw new Exception("成绩查询失败");
		}
		
		// 获得当前查询成绩
		Element tab = tables.get(0);
		if ( tab == null )
		{
			Log.i(TAG, "当前成绩模块为null");
			throw new Exception("成绩查询失败");
		}
		
		Elements trs = tab.select("tr");
		if(trs.size() <= 1)
			return;
		
		mScoreList = new ArrayList<ScoreBean>();
		// 跳过标题
		for ( int i = 1, len = trs.size(); i < len; i++ )
		{
			ScoreBean bean			= 	new ScoreBean();
			Element tr 				= 	trs.get(i);
			// 跳过查询时间和学期号
			bean.courseCode 		= 	tr.child(2).ownText();
			bean.courseName			= 	tr.child(3).ownText();
			bean.courseProperties	=	tr.child(4).ownText();
			bean.coursecredit		=	tr.child(5).ownText();
			bean.gradeDot			=	tr.child(6).ownText();
			bean.grade				=	tr.child(7).ownText();
			bean.replyGrade			=	tr.child(8).ownText();
			bean.college			=	tr.child(9).ownText();
			
			mScoreList.add(bean);
		} // for (...)
		
		Log.i(TAG, "解析成绩数据成功");
		
	} // readStrem

	public ArrayList<ScoreBean> getScoreList()
	{
		return this.mScoreList;
	}
	
	public void printData()
	{
		for ( int i = 0; i < mScoreList.size(); i++ )
		{
			ScoreBean bean = mScoreList.get(i);
			System.out.println(bean.courseCode);
			System.out.println(bean.courseName);
			System.out.println(bean.courseProperties);
			System.out.println(bean.coursecredit);
			System.out.println(bean.gradeDot);
			System.out.println(bean.grade);
			System.out.println(bean.replyGrade);
			System.out.println(bean.college);
		}
	}
}

